<template>
  <view class="big_box">
    <div class="big_header">
      <div class="big_header_top">
        <div style="width: 30%; border: 1px solid #fff; border-radius: 20px; padding: 10rpx 20rpx">
          <navigator style="display: flex; align-items: center; justify-content: space-between"
            class="win-info dis-ib mgr-2" url="/pages_h5/myCenter/index" open-type="switchTab"
            hover-class="other-navigator-hover">
            <image style="width: 60rpx; height: 60rpx; border-radius: 50%"
              v-if="userInfo.avatar && userInfo.avatar.includes('http')" :src="userInfo.avatar">
            </image>
            <image style="width: 60rpx; height: 60rpx; border-radius: 50%"
              src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/03/20/f_20250320164147A002.png"
              v-else-if="!userInfo.avatar"></image>
            <image v-else style="width: 60rpx; height: 60rpx; border-radius: 50%" :src="imgurl + userInfo.avatar">
            </image>

            <text v-if="userInfo.nickname" class="pdl-2">{{ userInfo.nickname.slice(0, 6) + (userInfo.nickname.length >
              6 ? '..' : '') }}</text>
            <text v-else class="pdl-2">未登录</text>
          </navigator>
        </div>
        <div style="width: 45%">
          <u-input customStyle="background: #fff;" placeholder="搜索" prefixIcon="search" fontSize="24"
            prefixIconStyle="font-size: 22px ;color: #909399" @input="onSearchInput"></u-input>
        </div>
        <div></div>
      </div>
      <div class="big_header_menu">
        <div v-for="(item, index) in menuData" style="width: 20%; text-align: center; margin-top: 20rpx"
          @click="gotoUrl(item)" :key="index">
          <image :src="imgurl + item.imageUrl" style="width: 80rpx; height: 80rpx"></image>
          <div style="margin: 3rpx">{{ item.categoryName }}</div>
        </div>
      </div>
    </div>
    <!-- <div class="button_weizhi" @click="getLocations()">获取地理位置</div> -->


    <div style="padding: 10px;padding-top: 550rpx;z-index: -1;" v-if="merData.length && merData">
      <div v-for="(item, index) in merData" :key="index" @click="goDetail(item)">
        <div
          style="background: #ffffff; margin-top: 10px; box-shadow: 0 0 25px 0 #ecf3ff; padding: 10px; border-radius: 5px">
          <div style="display: flex">
            <div style="width: 120rpx">
              <image
                :src="(item.merAvatar && item.merAvatar.indexOf('http')) !== -1 ? item.merAvatar : imgurl + item.merAvatar"
                style="width: 120rpx; height: 120rpx; border-radius: 5px"></image>
            </div>
            <div style="margin-left: 30rpx; display: grid">
              <div
                style="font-weight: bold; font-size: 14px;display: flex;justify-content: space-between;align-items: center;">
                {{ item.merName }}
                <span style="font-size: 22rpx;color: #999999;">{{ getKm(item.distance) }}</span>
              </div>
                      <div style="display: flex;flex-wrap: wrap;">
                        <!-- 默认显示消费返积分 -->
                        <div style="margin: 0 10rpx 0 0;">
                          <span style="font-size: 20rpx; color: #fe7f41; background-color: #fff1eb; padding: 3px 6px">消费返积分</span>
                        </div>
                        <!-- 当activityPlatformCommissionbl大于0时显示消费返物业费 -->
                        <div v-if="item.activityPlatformCommissionbl > 0" style="margin: 0 10rpx 0 0;">
                          <span style="font-size: 20rpx; color: #fe7f41; background-color: #fff1eb; padding: 3px 6px">消费返物业费</span>
                        </div>
                        <!-- 原有的分类标签，最多显示3个 -->
                        <div v-for="(category, index) in item.categoryName.split(',').splice(0, 3)" :key="'category-' + index"
                          style="margin: 0 10rpx 0 0 ;">
                          <span style="font-size: 20rpx; color: #fe7f41; background-color: #fff1eb; padding: 3px 6px">{{
                            category
                          }}</span>
                        </div>
                      </div>

              <div style="color: #808080; display: flex; align-items: center">
                <u-icon name="map" color="#808080" size="28"></u-icon>
                <span
                  style="margin-left: 4rpx; font-size: 24rpx; max-width: 470rpx;min-width: 470rpx; overflow: hidden; /*溢出的部分隐藏*/ white-space: nowrap; /*文本不换行*/ text-overflow: ellipsis">{{
                    item.merAddress
                  }}</span>
              </div>
            </div>
          </div>
          <div style="margin-left: 150rpx" v-for="(items, i) in item.activityList.slice(0, 2)" :key="i">
            <span style="color: #f86316">￥{{ items.price }}</span>
            <span style="padding-left: 10px; font-size: 10px; font-weight: bold">{{ items.name }}</span>
          </div>
        </div>
      </div>
      <div v-if="loading" style="text-align: center; padding: 10px">加载中...</div>
    </div>
    <div v-else
      style="text-align: center; padding: 10px; padding-top: 532rpx; display: flex; flex-direction: column; align-items: center">
      <image class="" mode="aspectFit"
        src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/03/25/zwsj_20250325090754A001.png"> </image>
      <span
        style="font-family: PingFangSC, PingFang SC; font-weight: 400; font-size: 28rpx; color: #a8a8a8; line-height: 40rpx; text-align: center; font-style: normal">暂无数据</span>
    </div>
    <div v-if="shouquan"
      style="position: fixed;bottom: 20rpx;width: 92%; display: flex;align-items: center;justify-content: space-between;padding: 20rpx 10rpx; background-color: rgba(0, 0, 0, 0.7);margin: 0 20rpx;border-radius: 20rpx;">
      <div class="leftcss">
        <div style="font-size: 28rpx;color: #fff;margin-bottom: 5rpx;">开启定位服务</div>
        <div style="font-size: 22rpx;color: #ecf3ff;margin-top: 5rpx;">开启后，将为您准确推荐附近吃喝玩乐</div>
      </div>
      <div class="rightcss" style="display: flex;align-items: center;">
        <button @click="getwxshezhi()"
          style="border-radius: 30rpx;background-color: #ff6507;color: #000;display: flex;align-items: center;justify-content: center;font-size: 24rpx;margin-right: 10rpx;">
          开启定位</button>
        <u-icon @click="shouquan = false" name="close-circle-fill" style="margin-left: 20rpx;" size="40"></u-icon>
      </div>
    </div>
  </view>
</template>

<script>
import { merCategory, getList } from "../../utils/api/api.js";
import { IMG_URL } from "../../config/index.js";
export default {
  data() {
    return {
      menuData: [],
      imgurl: IMG_URL,
      userInfo: '',
      pageNum: 1,
      pageSize: 10,
      total: '',
      merData: [],
      searchKeyword: "",
      loading: false, // 是否正在加载
      goodScroll: true, // 标记是否有更多数据
      categoryId: "", // 类别ID
      lat: '',
      lng: '',
      shouquan: true, // 标记是否授权获取位置
    };
  },
  /* 上拉加载 触底加载 */
  onReachBottom() {
    this.loadMoreData();
  },
  /* 下拉刷新 */
  onPullDownRefresh() {
    this.pageNum = 1;
    this.pageSize = 10;
    this.merData = [];
    this.getLocations(); // 获取微信授权位置
    this.getData();
    // 数据刷新完成后停止下拉刷新
    setTimeout(() => {
      uni.stopPullDownRefresh();
    }, 1000);
  },
  onLoad(option) {
    const xiaoxi = ''
    if (xiaoxi) {
      uni.showModal({

        title: '活动预热',
        content: xiaoxi,
        showCancel: false, // 不显示取消按钮
        // 确认按钮的文字自定义
        confirmText: "我已知晓",

        success: function (res) {
          if (res.confirm) {
            // 执行确认后的操作
          }
          else {
            // 执行取消后的操作
          }
        }
      })
    }
    if (option.shareId) {
      uni.setStorageSync('ebMerId', option.shareId)
      uni.setStorageSync('userType', 3)
    }
  },

  onShow() {
    this.userInfo = uni.getStorageSync("userInfo");
    this.getmerCategory();

    this.getPoint().then(() => {
      this.getData(); // 调用新集成的方法
      this.getLocations(); // 获取微信授权位置
      //  this.gologin(); // 登录验证
    }).catch((err) => {
      this.getmerCategory();
      this.getLocations(); // 获取位置失败时调用
      this.getData(); // 调用新集成的方法
    });
  },
  methods: {
    /* 加载更多 */
    loadMoreData() {
      if (this.pageNum * this.pageSize >= this.total) {
        uni.showToast({
          title: '没有更多数据了',
          icon: 'none'
        });
      } else {
        uni.showLoading({
          title: '加载中...'
        });
        this.pageNum++;
        this.getData();
      }
    },
    /* 打开微信授权定位 */
    getwxshezhi() {
      this.getLocations()
    },
    getLocations() {
      let that = this
      // 获取用户是否开启 授权获取当前的地理位置、速度的权限。
      uni.getSetting({
        success(res) {
          that.shouquan = false
          // 如果没有授权
          if (!res.authSetting['scope.userLocation']) {
            // 则拉起授权窗口
            uni.authorize({
              scope: 'scope.userLocation',
              success() {
                //点击允许后--就一直会进入成功授权的回调 就可以使用获取的方法了
                uni.getLocation({
                  type: 'wgs84',
                  success: function (res) {
                    that.x = res.longitude
                    that.y = res.latitude
                    that.shouquan = false
                    console.log('当前位置的经度：' + res.longitude)
                    console.log('当前位置的纬度：' + res.latitude)
                  }, fail(error) {
                    console.log('失败', error)
                  }
                })
              },
              fail(error) {
                //点击了拒绝授权后--就一直会进入失败回调函数--此时就可以在这里重新拉起授权窗口
                console.log('拒绝授权', error)
                uni.showModal({
                  title: '提示',
                  content: '若点击不授权，将无法使用位置功能',
                  cancelText: '不授权',
                  cancelColor: '#999',
                  confirmText: '授权',
                  confirmColor: '#f94218',
                  success(res) {
                    if (res.confirm) {
                      // 选择弹框内授权
                      uni.openSetting({
                        success(res) {
                          if (res.authSetting['scope.userLocation']) {
                            that.shouquan = false
                            that.getPoint().then(() => {
                              that.getmerCategory();
                              that.getData(); // 调用新集成的方法
                              return
                            })
                          } else {
                            that.shouquan = true
                            that.getPoint().then(() => {
                              that.getmerCategory();
                              that.getData(); // 调用新集成的方法
                              return
                            })
                          }

                        }
                      })
                    } else {
                      that.shouquan = true
                      that.getmerCategory();
                      that.getData()
                    }
                  }
                })
              }
            })
          } else {
            // 有权限则直接获取
            uni.getLocation({
              type: 'wgs84',
              success: function (res) {
                that.shouquan = false
                that.x = res.longitude
                that.y = res.latitude
              }, fail(error) {
                that.getmerCategory();
                that.getData(); // 调用新集成的方法
                uni.showToast({
                  title: '请打开手机定位使用！！！',
                  icon: 'none',
                })
                that.shouquan = true
              }
            })
          }
        }
      })

    },
    /* 获取距离 */
    getKm(distance) {
      if (distance) {
        if (distance >= 1000000) {
          return ''; // 大于等于1000公里时不展示
        } else if (distance >= 1000) {
          return (distance / 1000).toFixed(1) + 'km';
        } else if (distance <= 1000) {
          return Number(distance).toFixed(1) + 'm';
        }
      }
      return distance;
    },
    /* 获取用户位置 */
    /* 获取用户位置 */
    getPoint() {
      return new Promise((resolve, reject) => {
        uni.getLocation({
          type: 'WGS84',
          altitude: true,
          geocode: true,
          success: (res) => {
            console.log("🚀 ~ returnnewPromise ~ res:", res)
            uni.setStorageSync('user_latitude', res.latitude);
            uni.setStorageSync('user_longitude', res.longitude);
            this.lat = res.latitude;
            console.log("🚀 ~ returnnewPromise ~ this.lat:", this.lat)
            this.lng = res.longitude;
            resolve();
          },
          fail: (err) => {
            console.log("获取位置失败", err);
            reject(err);
          },
        });
      });
    },
    /** 跳转详情页 */
    goDetail(data) {
      uni.navigateTo({
        url: "/pages_h5/index/components/detail?id=" + data.id,
      });
    },
    // 头部跳转转设置
    getmerCategory() {
      merCategory().then((res) => {
        this.menuData = (res.data || [])
          .filter((item) => item.categoryName !== "线上商城") // 过滤掉 categoryName 为 '线上商城' 的项
          .map((item) => {
            return {
              ...item,
              jumpUrl: "/pages_h5/index/merList?categoryId=" + item.merchantCategoryId,
            };
          });
      });
    },
    // 查询商户列表（新集成方法）
    getData(serch = this.searchKeyword) {
      uni.showLoading({
        title: '加载中...'
      });

      if (!this.goodScroll) {
        uni.hideLoading()
        return;
      };

      const params = {
        merName: serch,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        categoryId: this.categoryId,
        lat: this.lat,
        lng: this.lng,
        isZxmer: serch ? '' : 0,
        status: 0,
		 isVendor: 0,
      };
      if (serch) {
        delete params.isZxmer;
      }
      getList(params)
        .then((res) => {
          this.loading = false;
          this.total = res.total;
          if (this.pageNum == 1) {
            // 第一次请求时，清空原有数据
            this.merData = res.rows;
            this.merData.find((item) => item.id == 100).distance = "<100m"
            uni.hideLoading()
          } else {
            // 滚动加载，追加数据
            this.merData = this.merData.concat(res.rows);
            uni.hideLoading()
          }
          // 如果有活动列表，限制最多显示2条
          (res.rows || []).forEach((item) => {
            if (item.activityList.length > 2) {
              item.activityList = item.activityList.slice(0, 2);
            }
          });
        })
        .catch(() => {
          this.loading = false;
          uni.hideLoading()
        });
    },
    // 搜索方法
    onSearchInput(event) {
      this.searchKeyword = event;
      this.pageNum = 1; // 搜索时重置页码
      this.merData = []; // 清空商户列表
      this.categoryId = ""; // 搜索时重置类别ID
      this.getData(); // 调用新集成的方法
    },
    // 点击头部跳转商户
    gotoUrl(item) {
      if (item.categoryName == "大牌点餐") {
        uni.navigateTo
        ({
          url:'/myPackage/pages/tiaozhuan/index',
        });
      } else {
        uni.navigateTo({
          url: item.jumpUrl,
        });
      }
    },


  },
};
</script>

<style scoped>
.big_box {
  font-size: 24rpx;
  height: 100vh;
  /* 设置为视窗高度 */
}

.big_header {
  background-image: url("https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/03/25/header-bgi_20250325162639A027.png");
  width: 100%;
  height: 550rpx;
  position: fixed !important;
  z-index: 10;
}

.big_header_top {
  height: 100rpx;
  background-color: rgb(255, 222, 203);
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.top_input {
  width: 100%;
  background: #fff;
  height: 70rpx;
  padding-left: 15px;
  border-radius: 5px;
}

.u-border {
  border: none;
  background-color: #fff;
}

.u-input {
  background: #fff;
}

.big_header_menu {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}
</style>
